<?php

namespace App\Jobs;

use App\Qrcode;
use App\User;
use Carbon\Carbon;
use Intervention\Image\Facades\Image;
use SimpleSoftwareIO\QrCode\Facades\QrCode as IOQrCode;
use EasyWeChat\Message\Image as WMImage;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class SendUserQrcode implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    protected $user;
    protected $qrcode;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct(User $user, Qrcode $qrcode)
    {
        $this->user = $user;
        $this->qrcode = $qrcode;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $wechat = app('wechat');

        $path = public_path('/upfiles/qrcode/' . $this->user->id . '_' . Carbon::now()->format('YmdHis') . '.png');

        $qrcode = $wechat->qrcode;
        $data = $qrcode->temporary($this->user->id, 2592000);
        $source = IOQrCode::format('png')->size($this->qrcode->size)->margin(1)->generate($data->url);
        $image = Image::make(public_path($this->qrcode->background));
        $image->insert($source, 'top-left', $this->qrcode->top, $this->qrcode->left);
        $image->save($path);

        try {
            $material = $wechat->material_temporary;
            $data = $material->uploadImage($path);
            $image = new WMImage(['media_id' => $data->media_id]);

            $wechat->staff->message($image)->to($this->user->openid)->send();
        } catch (\Exception $e) {
        }
    }
}
